import React from 'react';
import { history } from 'umi';
import { Button,Modal,Checkbox,Tag, Toast } from 'antd-mobile';
import styles from './index.less';
import right from '@/assets/icon/ic_right.svg';
import ic_error from '@/assets/icon/ic_error.svg';
import { upsetArray } from '@/utils';
import QueueAnim from 'rc-queue-anim';
import { getQuestionStatics,questionRelease } from '@/services/edu'
import { index } from './utils';
import {Rate} from 'antd'

const AgreeItem = Checkbox.AgreeItem;
import Countdown from 'react-countdown';
type answer = {
  label: string | React.ReactNode;
  value: string | number;
}
export interface TopicProps {
  isCheckbox?: boolean; //是否多选 默认false
  submitDisabled?: boolean; //提交按钮禁止操作 默认false
  defaultValue?: number[] | string[]; //已选中的默认值
  question: string | React.ReactNode; //问题
  options: answer[];  //答案列表
  answer: number[] | string[];  //正确答案
  value: number[] | string[]; //选中的答案
  current: number;  //当前第几题
  total: number;  //一共多少题
  title?: string; // 标题
  parse?: string | React.ReactNode; //问题解析
  onChange: (value: number[] | string[]) => void; //点击切换
  onSubmit: (value: number[] | string[],data:any) => void; //点击提交按钮操作
  correctNumber?: number; //正确的数量
  failNumber?: number;  //错误的数量
  onPre?: () => void; //点击上一题
  onNext?: () => void; //点击下一题
  footerExtra?: string | React.ReactNode; //底部元素
  upset?: boolean;  //是否打乱
  type: 0 | 1 | 2;  //0模拟 1练习  2考试
  timeLimit?:number; //限制时间 单位 分钟
  isRight?:boolean;
  isError?:boolean; // 是否错题本
  topicInfo?:any;
  id:number|string;
  forceEnd?:(value: number[] | string[]) => void; // 强制提交

}
export default class Topic extends React.Component<TopicProps, any> {

  static formatOptions = (data: any[], label: string = 'name', value: string = 'id') => {//格式化options数据
    return data.map(item => ({
      label: item[label],
      value: item[value],
    }))
  }
  static index = index
  constructor(props) {
    super(props);
    this.state = {
      value: props.value,
      showResult:false,
      initTime:Date.now(),
      submitModal:false,
      hasReturn:false,
      statics:{}
    }
  }
  componentDidMount =async()=>{
    const res = await getQuestionStatics({questionId:this.props.id})
    if(res?.code===1){
      this.setState({statics:res?.response})
    }
  }
  onCheckboxChange = (item) => {  //多选
    const { defaultValue=[] } = this.props;
    const { value :val = defaultValue } = this.state;
    const value = new Set([...val]);
    if (value.has(item.value)) {
      value.delete(item.value);
    } else {
      value.add(item.value);
    }
    this.setState({
      value: [...value],
    })
    this.props.onChange([...value])
  }
  onRadioChange = (item) => { //单选
    this.setState({
      value: [item.value]
    })
    // 单选题 自动提交
    // if(!this.state.showResult){
    //   this.setState({value:[]})
    //   return this.props.onSubmit([item.value],this.props.topicInfo)
    // }
    
    this.props.onChange([item.value])
  }
  renderAnswer = (item, index) => {
    const { isCheckbox, defaultValue = [] } = this.props;
    const { value = defaultValue } = this.state;
    return <div
      key={`answer-${index}`}
      onClick={() => {
        if (isCheckbox) {
          this.onCheckboxChange(item)
        } else {
          this.onRadioChange(item)
        }
      }}
    >
      <span>
        <span className={value.indexOf(item.value) !== -1 ? styles.active : undefined}>{Topic.index[index]}</span>
      </span>
      <span>
        {item.label}
      </span>
    </div>
  }

  submit = () => {
    const {
      current,
      total,
      type
    } = this.props
    const {
      value
    } = this.state
    if (!value && !this.props.defaultValue) {
      return;
    } else {
      // 最后一题
      if(current === total && type!==1){
        this.setState({submitModal:true})
      }else{
        this.props.onSubmit(value || this.props.defaultValue,this.props.topicInfo);
        this.setState({value:[]})
      }
      
    }
  }
  hasReturn=false
  renderer = ({ hours, minutes, seconds, completed }) => {
    const {
      forceEnd,
      timeLimit
    } = this.props
    const {
      value,
    } = this.state
    if (completed&&!this.hasReturn) {
      this.hasReturn=true
   
      if(forceEnd && typeof forceEnd === 'function'){
        forceEnd(value)
      }
      return false
    } else {
      // Render a countdown
    return hours>0?<span>倒计时：{hours}:{minutes}:{seconds}</span>:<span>倒计时：{minutes}:{seconds}</span>;
    }
  };
  handleSubmitModal = ()=> {
    const {
      value
    } = this.state;
    this.props.onSubmit(value || this.props.defaultValue,this.props.topicInfo)
    // 最后提交
    this.setState({submitModal:false})
  }
  handleShowResult =()=>{
    // localStorage.setItem('showResult',this.state.showResult?'':'1')
    this.setState({showResult:!this.state.showResult})
  }
  handleRelease = async(id)=>{
    const res = await questionRelease({questionId:id})
    if(res?.code===1){
      Toast.success('释放成功')
    }
  }
  render() {
    const { question, 
      answer,
      isRight,
      topicInfo,
      isError,
      current, total,title, parse, submitDisabled = false, defaultValue = [], onPre, isCheckbox, correctNumber, failNumber, options, upset,type,timeLimit=60 } = this.props;
    const { value = defaultValue,showResult,submitModal,statics } = this.state;
    return <div className={styles.container}>
      <div className={styles.title}>
        {(type===1&&topicInfo.tagValue)?<div className={styles.tag}>{
            topicInfo.tagValue.split(',').map((item,i)=><Tag key={i}>{item}</Tag>)
          }</div>:<span dangerouslySetInnerHTML={{__html:title}}></span>}
        <span className={styles.current}>
          {current}/{total}
        </span>
      </div>

      <div className={styles.question}>
        <div className={styles.sign}>{isCheckbox ? '多选' : '单选'}</div>
        <div className={styles.contant}>{question}</div>
       
      </div>

      <div className={styles.answers}>
        {
          options.map(this.renderAnswer)
        }
      </div>
      <div className={styles.showResult}>
        <AgreeItem checked={showResult} onChange={()=>this.handleShowResult()}>打开答案提示</AgreeItem>
        {isError?<a onClick={()=>this.handleRelease(topicInfo.id)}>释放本题</a>:<a onClick={()=>history.push(`/question?id=${topicInfo.id}`)}>本题有问题</a>}
      </div>
      {showResult&&<QueueAnim type="bottom" leaveReverse>
      <div className={styles.splitter} />
      {/* <div className={styles.answer}>正确答案：{answer} 你的答案：C 回答错误</div> */}
      <div className={styles.rightAnswers}>
          <span>正确答案：{answer.join(' ')}</span>
          {
            isRight ? <span className='text-success'>回答正确</span> : <span className="text-error">{value.length?'回答错误':'未做答'}</span>
          }
        </div>
      <div className={styles.statistics}>共被作答<span>{statics.donePerCount||'-'}</span>次，正确率为<span>{statics.correctPercent||'-'}%</span></div>
      <div className={styles.parse}>
        <div>
          <i />解析  <Rate allowHalf value={topicInfo.difficult}/>
        </div>
        {topicInfo.analyze&& <div dangerouslySetInnerHTML={{__html:topicInfo.analyze}}>
        </div>}
      </div>
     {topicInfo.examPoint&&<div style={{paddingTop:0}} className={styles.parse}>
        <div>
          <i />考点 
        </div>
        <div dangerouslySetInnerHTML={{__html:topicInfo.examPoint}}>
        </div>
      </div>}
      </QueueAnim>}

      <div className={`${styles.footer} fixed_bottom`}>
        <Button onClick={()=>onPre()} className={styles.button} disabled={current===1} size='small' type='primary'>
         上一题 
        </Button>
        <Button onClick={()=>this.submit()} disabled={submitDisabled || value.length === 0} className={styles.button} size='small' type='primary'>
         {total>current?'下一题':'完成练习' }
        </Button>
        {/* <Button onClick={()=>this.submit()} disabled={submitDisabled || value.length === 0} className={styles.button} size='small' type='primary'>提交答案</Button> */}
      </div>
      <Modal
          visible={submitModal}
          transparent
          closable={true}
          maskClosable={false}
          onClose={()=>this.setState({submitModal:false})}
          title=""
          footer={[{ text: '提交', onPress: this.handleSubmitModal}]}
          // afterClose={() => { alert('afterClose'); }}
        >
          试卷完成，提交考卷？
        </Modal>
    </div>
  }
}